package com.cyd.handler;

import com.cyd.exception.AgeException;
import com.cyd.exception.NameException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author keyer
 * @Description : 控制器增强，捕获异常
 * Created by cyd on 2021-05-16 23:09:40
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 用于捕获name异常，只要抛出NameException，即可捕获
     */
    @ExceptionHandler(value = NameException.class)
    public ModelAndView doNameException(Exception exception) {

        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "您的姓名必须是zs");

        mv.addObject("ex", exception);
        mv.setViewName("nameExceptionPage");
        return mv;
    }

    /**
     * 用于捕获age异常，只要抛出NameException，即可捕获
     */
    @ExceptionHandler(value = AgeException.class)
    public ModelAndView doAgeException(Exception exception) {

        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "您的年龄必须是0-80之间");

        mv.addObject("ex", exception);
        mv.setViewName("ageExceptionPage");
        return mv;
    }

    /**
     * 处理其他未定义异常的方法，只能有一个
     *
     * @param exception 异常
     * @return mv
     */
    @ExceptionHandler
    public ModelAndView doOtherException(Exception exception) {

        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "出现未定义异常");

        mv.addObject("ex", exception);
        mv.setViewName("defaultExceptionPage");
        return mv;
    }
}
